<template>
  <div class="app-container">
    <div class="filter-container">
      <div class="formContainer">
        <el-input v-model="listQuery.keyword" placeholder="请输入关键词" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
        <el-button class="buttons" @click="handleFilter">
          搜索
        </el-button>
        <el-button v-if="multipleSelection.length>0" clsss="buttons" @click="batchDel">批量删除</el-button>
      </div>
    </div>
    <el-table
      :key="tableKey"
      :data="list"
      style="width: 100%;"
      fit
      :header-cell-style="{background:'#ebebeb',height:'#54px'}"
      @sort-change="sortChange"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" align="center" />
      <el-table-column label="ID" prop="id" sortable="custom" align="center" width="80" :class-name="getSortClass('id')">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="用户名" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.username }}</span>
        </template>
      </el-table-column>
      <el-table-column label="标题" align="center">
        <template slot-scope="{row}">
          <span>{{ row.title }}</span>
        </template>
      </el-table-column>
      <el-table-column label="地址" min-width="150px">
        <template slot-scope="{row}">
          {{ row.referer }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template v-if="row.id!=1" slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleView(row)">
            查看
          </el-button>
          <el-popconfirm
            confirm-button-text="好的"
            cancel-button-text="不用了"
            icon="el-icon-info"
            icon-color="red"
            title="删除后不可以恢复，确定删除吗？"
            @onConfirm="handleDelete(row,$index)"
          >
            <el-button slot="reference" size="mini" type="danger">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.per_page" @pagination="getList" />
    <!-- 编辑、 添加弹框表单 -->
    <el-dialog title="查看" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
      <el-form label-position="left" label-width="100px" style="width: 400px; margin-left:50px;">
        <el-form-item label="管理员" prop="groupid">
          <span>{{ rows.manager_name }}</span>
        </el-form-item>
        <el-form-item label="标题" prop="username">
          <span>{{ rows.title }}</span>
        </el-form-item>
        <el-form-item label="接口地址" prop="username">
          <span>{{ rows.url }}</span>
        </el-form-item>
        <el-form-item label="内容" prop="password">
          <span>{{ rows.content }}</span>
        </el-form-item>
        <el-form-item label="时间" prop="icon">
          <span>{{ rows.addtime }}</span>
        </el-form-item>
        <el-form-item label="终端">
          <span>{{ rows.agent }}</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          关闭
        </el-button>
      </div>
    </el-dialog>
    <!--  -->
    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel" />
        <el-table-column prop="pv" label="Pv" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">Confirm</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { fetchList, add, edit, del, rows } from '@/api/managerLog'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { parseTime } from '@/utils/index'
const calendarTypeOptions = [
  { key: 0, display_name: '全部' },
  { key: 'image', display_name: '图片' },
  { key: 'audio', display_name: '音频' },
  { key: 'text', display_name: '文档' },
  { key: 'rar', display_name: '文档' }
]
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})
export default {
  name: 'AttachmentIndex',
  components: { Pagination },
  filters: {
    statusFilter(status) {
      const statusMap = {
        normal: '正常',
        hidden: '隐藏'
      }
      return statusMap[status]
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  data() {
    return {
      multipleSelection: [],
      iconsShow: false,
      tableKey: 0,
      list: null,
      total: 0,
      ids: null,
      listQuery: {
        page: 1,
        per_page: 15,
        importance: undefined,
        keyword: null,
        type: undefined,
        sort: '+id'
      },
      calendarTypeOptions,
      importanceOptions: [1, 2, 3],
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      statusOptions: { 'normal': '正常', 'hidden': '隐藏' },
      showReviewer: false,
      rows: {
        id: null,
        pid: 0,
        title: '',
        name: '',
        url: '',
        ismenu: 1,
        status: 'normal',
        remark: '',
        face: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '更新',
        create: '添加'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        pid: [{ required: true, message: 'type is required', trigger: 'change' }],
        timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
        title: [{ required: true, message: 'title is required', trigger: 'blur' }]
      },
      downloadLoading: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 获取列表数据
    getList() {
      var that = this
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        this.list = response.data.data
        this.total = response.data.total
        setTimeout(() => {
          that.listLoading = false
        }, 1.5 * 1000)
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetRows() {
      this.rows = {
        id: 0,
        pid: 0,
        title: '',
        name: '',
        url: '',
        ismenu: 1,
        status: 'normal',
        remark: ''
      }
    },
    handleCreate() {
      this.resetRows()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 新增提交方法
    createData() {
      // const that = this
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          add(this.rows).then(response => function(params) {
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Created Successfully',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    // 查看详情
    handleView(row) {
      const that = this
      rows(row.id).then(function(res) {
        that.rows = Object.assign({}, res.data)
      })
      this.dialogStatus = 'view'
      this.dialogFormVisible = true
    },
    updateData() {
      const that = this
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.rows)
          // ids, title, name, icon, remark, status, type, url
          edit(tempData.uuid,
            tempData.pid,
            tempData.title,
            tempData.name,
            tempData.icon,
            tempData.remark,
            tempData.status,
            tempData.type,
            tempData.url).then((res) => {
            const index = that.list.findIndex(v => v.id === that.rows.ids)
            that.list.splice(index, 1, that.rows)
            that.dialogFormVisible = false
            that.$notify({
              title: 'Success',
              message: res.msg || '编辑成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    // 删除操作
    handleDelete(row, index) {
      this.delOpreat(row.id)
      this.list.splice(index, 1)
    },
    delOpreat(ids) {
      del(ids)
      this.$notify({
        title: '操作提示',
        message: '删除成功',
        type: 'success',
        duration: 2000
      })
    },
    handleDownload() {
      this.downloadLoading = true
      // import('@/vendor/Export2Excel').then(excel => {
      //   const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
      //   const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
      //   const data = this.formatJson(filterVal)
      //   excel.export_json_to_excel({
      //     header: tHeader,
      //     data,
      //     filename: 'table-list'
      //   })
      //   this.downloadLoading = false
      // })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
      const idsarr = []
      val.forEach(element => {
        idsarr.push(element.id)
      })
      this.ids = idsarr.join(',')
    },
    batchDel() {
      if (this.multipleSelection.length) {
        this.downloadLoading = true
        this.delOpreat(this.ids)
        this.getList()
      } else {
        this.$message({
          message: 'Please select at least one item',
          type: 'warning'
        })
      }
    }
  }
}
</script>
